package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.commit.MyThreadLocal;
import com.itheima.commit.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String uri = request.getRequestURI();

        //定义放行路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //调用方法
        boolean match = match(urls, uri);

        //判断请求路径中是否包含需要放行的路径，包含直接放行
        if (match) {
            filterChain.doFilter(request,response);
            MyThreadLocal.remove();
            return;
        }

        //判断当前是否为登录状态
        if (request.getSession().getAttribute("employee") != null) {

            Long employee = (Long) request.getSession().getAttribute("employee");
            MyThreadLocal.setThreadLocal(employee);

            filterChain.doFilter(request,response);
            MyThreadLocal.remove();
            return;
        }

        if (request.getSession().getAttribute("user") != null) {

            Long user = (Long) request.getSession().getAttribute("user");
            MyThreadLocal.setThreadLocal(user);

            filterChain.doFilter(request,response);
            MyThreadLocal.remove();
            return;
        }

        //响应前端需要的“NOTLOGIN”数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    //定义方法，需要放行路径中是否包含请求路径
    public boolean match(String[] urls, String uri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
